<?php
/*
  功能：抽奖奖品表 model
  作者：cxm
  时间：2019-10-23
*/

namespace App\Models;

use DateTimeInterface;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use DB;

class AwardGoods extends BaseModel {
    use SoftDeletes;
    protected $dates = ['deleted_at']; //开启deleted_at
    protected $table='award_goods';  //绑定表
    // 用户是否获取该商品、固定奖品是否支付
    protected $appends = ['user_is_get'];

    /**
     * 当前登录用户是否已经领取该商品
     */
    public function getUserIsGetAttribute(){
        if (!isset($this->attributes['id']) || empty($this->attributes['id'])) {
            return false;
        }
        // 商品ID
        $goods_id = $this->attributes['id'];
        // 用户ID
        $user = auth()->guard('api')->user();
        if (!$user) {
            return false;
        }
        $user_id = $user['id'];
        $history =  AwardHistory::userGetNum($user_id,$goods_id);
        if ($history > 0) {
            return true;
        }
        return false;
    }


    /**
     * 活动
     */
    public function activity(){
        return $this->hasOne(Activity::class,'id','activity_id');
    }

    /**
     * 文件
     */
    public function file(){
        return $this->hasOne(File::class,'id','img');
    }

    /**
     * 该奖品下的礼物
     */
    public function goods(){
        return $this->hasMany(AwardGoodsClass::class,'award_goods_id','id');
    }

    /**
     * 抽奖奖品
     * @param $activity_id 活动ID
     * @return mixed
     */
    public static function getGoodsLists($activity_id){
        $act = Activity::find($activity_id); // 活动信息
        $start_time = strtotime($act->start_time);
        $end_time = strtotime($act->end_time);
        // 查询中奖数量
        $table_prefix = DB::getTablePrefix();
        $builder = AwardHistory::where('activity_id',$activity_id)
            ->whereRaw("{$table_prefix}award_history.award_id = {$table_prefix}award_goods.id")
//            ->where('draw_time','>',$start_time)
//            ->where('draw_time','<',$end_time)
            //->where(DB::raw("UNIX_TIMESTAMP({$table_prefix}award_history.draw_time) > {$start_time} AND UNIX_TIMESTAMP({$table_prefix}award_history.draw_time) < {$end_time}"))
            ->select(DB::raw("count(*)"));
        // 生成sql语句
        $bindings = $builder->getBindings();
        $sql = str_replace('?', '%s', $builder->toSql());
        $sql = sprintf($sql, ...$bindings);
        $data = self::select(
            'award_goods.id',
            'award_goods.type',
            'award_goods.name as goods_name',
            'award_goods.stock',
            'award_goods.un_stock',
            'award_goods.probability',
            'award_goods.max_num',
            'award_goods.img',
            'award_goods.is_get',
            DB::raw("({$sql}) as sold")
        )
        ->where('award_goods.activity_id',$activity_id)
        ->where('award_goods.is_show',1)
        ->with([
            'file'  => function ($query) {
                $query->select('id','path');
            },
            'goods'
        ])
        ->get()->toArray();
        return $data;
    }

    /**
     * 根据商品查询商品名称
     * @param $goods_id 商品ID
     * @return mixed
     */
    public static function getName($goods_id){
        return self::where('id',$goods_id)->value('name');
    }

    /**
     * 根据商品获取某个字段的值
     * @param $goods_id 商品ID
     * @param $field 字段
     * @return mixed
     */
    public static function getFieldValue($goods_id,$field){
        return self::where('id',$goods_id)->value($field);
    }

    /**
     * 获取谢谢参与的ID
     * @param int $activity_id 活动ID
     * @return mixed
     */
    public static function getThanksId($activity_id){
        return self::where('activity_id',$activity_id)
            ->where('name','谢谢参与')
            ->value('id');
    }
}